package com.erp.statistics.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.erp.statistics.order.mapper.ErpChildOrderStatisticsMapper;
import com.erp.statistics.order.mapper.ErpOrderInfoStatisticsMapper;
import com.erp.statistics.order.service.IErpOrderInfoStatisticsService;
import com.ruoyi.ae.api.RemoteAeOrderAddrService;
import com.ruoyi.ae.api.domain.AeStoreOrderReceiptAddress;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.oldUtils.StringUtils;
import com.ruoyi.freight.api.RemoteFreightService;
import com.ruoyi.freight.api.domain.ErpProductExistingFreightRecord;
import com.ruoyi.gather.api.*;
import com.ruoyi.gather.api.domain.*;
import com.ruoyi.order.api.RemoteErpChildOrderService;
import com.ruoyi.order.api.RemoteErpOrderService;
import com.ruoyi.order.api.domain.ErpSellerChildOrder;
import com.ruoyi.order.api.domain.ErpSellerOrder;
import com.ruoyi.order.api.domain.ErpSellerOrderExtend;
import com.ruoyi.shop.api.RemoteSellerStoreService;
import com.ruoyi.shop.api.domain.ErpSellerStoreEmpower;
import com.ruoyi.statistics.api.domain.ErpChildOrderStatistics;
import com.ruoyi.statistics.api.domain.ErpOrderInfoStatistics;
import com.ruoyi.system.api.RemoteDictDataService;
import com.ruoyi.system.api.RemoteSysConfigService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 * 订单信息统计Service业务层处理
 *
 * @author erp
 * @date 2023-07-19
 */
@RequiredArgsConstructor
@Service
public class ErpOrderInfoStatisticsServiceImpl implements IErpOrderInfoStatisticsService {

    @Resource
    private RemoteUsdExchangeService remoteUsdExchangeService;
    @Resource
    private RemoteSellerStoreService remoteSellerStoreService;
    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private RemoteSellerStoreProductService remoteSellerStoreProductService;
    @Resource
    private RemoteCollectProductService remoteCollectProductService;
    @Resource
    private RemoteErpChildOrderService remoteErpChildOrderService;
    @Resource
    private RemoteErpOrderService remoteErpOrderService;
    @Resource
    private RemoteAeOrderAddrService remoteAeOrderAddrService;
    @Resource
    private RemoteDictDataService remoteDictDataService;
    @Resource
    private RemoteCollectProductSkuPriceService remoteCollectProductSkuPriceService;
    @Resource
    private RemoteCollectProductSkuService remoteCollectProductSkuService;
    @Resource
    private RemoteFreightService remoteFreightService;
    @Resource
    private RemoteSysConfigService configService;

    private final ErpOrderInfoStatisticsMapper baseMapper;
//    private final IErpUsdExchangeService usdExchangeService;
//    private final IErpSellerChildOrderService childOrderService;
//    private final ErpSellerChildOrderMapper childOrderMapper;
//    private final AeStoreOrderReceiptAddressMapper addressMapper;
//    private final IErpCollectProductSkuPriceService productSkuPriceService;
//    private final ErpCollectProductSkuMapper collectProductSkuMapper;
//    private final ErpCollectProductExpandMapper collectProductExpandMapper;
//    private final IErpProductFreightService productFreightService;
//    private final IErpCommonProductFreightService commonProductFreightService;
//    private final ConfigService configService;
//    private final IErpSellerStoreEmpowerService empowerService;
//    private final ErpSellerStoreEmpowerMapper empowerMapper;
//    private final ISysUserService userService;
    private final ErpChildOrderStatisticsMapper childOrderStatisticsMapper;
//    private final DictService dictService;
//    private final SysDictDataMapper dictDataMapper;
//    private final ErpSellerOrderMapper sellerOrderMapper;
//    private final ErpSellerChildOrderExtendMapper childOrderExtendMapper;
//    private final ErpSendOutGoodsMapper sendOutGoodsMapper;
//    private final ErpSellerOrderExtendMapper orderExtendMapper;
//    private final ErpCollectProductMapper collectProductMapper;
//    private final ErpSellerStoreProductMapper erpSellerStoreProductMapper;
//

    /**
     * 根据订单号，查询订单统计信息
     * @param orderId
     * @return
     */
    @Override
    public ErpOrderInfoStatistics queryByOrderId(String orderId){
        return baseMapper.selectOne(new LambdaQueryWrapper<ErpOrderInfoStatistics>()
                .eq(ErpOrderInfoStatistics::getOrderId, orderId));

    }

//    /**
//     * 查询订单信息统计
//     */
//    @Override
//    public ErpOrderInfoStatisticsVo queryById(Long id) {
//        return baseMapper.selectVoById(id);
//    }
//
//    /**
//     * 查询订单信息统计列表
//     */
//    @Override
//    public TableDataInfo<ErpOrderInfoStatisticsVo> queryPageList(ErpOrderInfoStatisticsBo bo, PageQuery pageQuery) {
//        Page<ErpOrderInfoStatisticsVo> result = baseMapper.findAllStatics(pageQuery.build(), bo);
//        List<ErpOrderInfoStatisticsVo> records = result.getRecords();
//        if (ObjectUtils.isNotEmpty(records)) {
//            records.forEach(vo -> {
//                Long orderId = vo.getOrderId();
//                LambdaQueryWrapper<ErpChildOrderStatistics> queryWrapper = new LambdaQueryWrapper<ErpChildOrderStatistics>().eq(ErpChildOrderStatistics::getOrderId, orderId);
//                List<ErpChildOrderStatisticsVo> erpChildOrderStatisticsVos = childOrderStatisticsMapper.selectVoList(queryWrapper);
//                vo.setChildOrderStatisticsVoList(erpChildOrderStatisticsVos);
//            });
//        }
//        return TableDataInfo.build(result);
//    }
//
//    /**
//     * 查询订单信息统计列表
//     */
//    @Override
//    public List<ErpOrderInfoStatisticsVo> queryList(ErpOrderInfoStatisticsBo bo) {
//        LambdaQueryWrapper<ErpOrderInfoStatistics> lqw = buildQueryWrapper(bo);
//        return baseMapper.selectVoList(lqw);
//    }
//
//    private LambdaQueryWrapper<ErpOrderInfoStatistics> buildQueryWrapper(ErpOrderInfoStatisticsBo bo) {
//        Map<String, Object> params = bo.getParams();
//        LambdaQueryWrapper<ErpOrderInfoStatistics> lqw = Wrappers.lambdaQuery();
//        lqw.eq(bo.getOrderId() != null, ErpOrderInfoStatistics::getOrderId, bo.getOrderId());
//        lqw.eq(StringUtils.isNotBlank(bo.getPayPrice()), ErpOrderInfoStatistics::getPayPrice, bo.getPayPrice());
//        lqw.eq(StringUtils.isNotBlank(bo.getAfflicateFeeRate()), ErpOrderInfoStatistics::getAfflicateFeeRate, bo.getAfflicateFeeRate());
//        lqw.eq(StringUtils.isNotBlank(bo.getEscrowFeeRate()), ErpOrderInfoStatistics::getEscrowFeeRate, bo.getEscrowFeeRate());
//        lqw.eq(StringUtils.isNotBlank(bo.getProfit()), ErpOrderInfoStatistics::getProfit, bo.getProfit());
//        lqw.eq(StringUtils.isNotBlank(bo.getCountry()), ErpOrderInfoStatistics::getCountry, bo.getCountry());
//        lqw.eq(StringUtils.isNotBlank(bo.getLogisticsCode()), ErpOrderInfoStatistics::getLogisticsCode, bo.getLogisticsCode());
//        lqw.eq(StringUtils.isNotBlank(bo.getDeptId()), ErpOrderInfoStatistics::getDeptId, bo.getDeptId());
//        lqw.eq(StringUtils.isNotBlank(bo.getStoreId()), ErpOrderInfoStatistics::getStoreId, bo.getStoreId());
//        lqw.like(StringUtils.isNotBlank(bo.getStoreUserName()), ErpOrderInfoStatistics::getStoreUserName, bo.getStoreUserName());
//        lqw.eq(StringUtils.isNotBlank(bo.getLogisticsPrice()), ErpOrderInfoStatistics::getLogisticsPrice, bo.getLogisticsPrice());
//        lqw.eq(StringUtils.isNotBlank(bo.getRevision()), ErpOrderInfoStatistics::getRevision, bo.getRevision());
//        return lqw;
//    }
//
//    /**
//     * 新增订单信息统计
//     */
//    @Override
//    public Boolean insertByBo(ErpOrderInfoStatisticsBo bo) {
//        ErpOrderInfoStatistics add = BeanUtil.toBean(bo, ErpOrderInfoStatistics.class);
//        validEntityBeforeSave(add);
//        boolean flag = baseMapper.insert(add) > 0;
//        if (flag) {
//            bo.setId(add.getId());
//        }
//        return flag;
//    }
//
//    /**
//     * 修改订单信息统计
//     */
//    @Override
//    public Boolean updateByBo(ErpOrderInfoStatisticsBo bo) {
//        ErpOrderInfoStatistics update = BeanUtil.toBean(bo, ErpOrderInfoStatistics.class);
//        validEntityBeforeSave(update);
//        return baseMapper.updateById(update) > 0;
//    }
//
//    /**
//     * 保存前的数据校验
//     */
//    private void validEntityBeforeSave(ErpOrderInfoStatistics entity) {
//        //TODO 做一些数据校验,如唯一约束
//    }
//
//    /**
//     * 批量删除订单信息统计
//     */
//    @Override
//    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
//        if (isValid) {
//            //TODO 做一些业务上的校验,判断是否需要校验
//        }
//        return baseMapper.deleteBatchIds(ids) > 0;
//    }
//

    @Override
    public int saveOrderProfitInfo(ErpSellerOrder sellerOrder, List<ErpSellerChildOrder> childOrderList) {
        Long orderId = sellerOrder.getOrderId();
        String payCurrencyCode = sellerOrder.getPayCurrencyCode();
        if (childOrderList.size() == 0) {
            return 0;
        }
        // 根据货币获取当时最新汇率
        if (StringUtils.isEmpty(payCurrencyCode)) {
            payCurrencyCode = childOrderList.get(0).getProductCurrencyCode();
        }
        BigDecimal exchange = null;
        R<Object> usdExchangeR = remoteUsdExchangeService.getExchangeByTime(sellerOrder.getGmtCreate(), payCurrencyCode);
        if(usdExchangeR.getCode() != 200 || usdExchangeR.getData() == null){
            return 0;
        }else {
            exchange = new BigDecimal(usdExchangeR.getData().toString()).movePointLeft(2);
            if (exchange.compareTo(BigDecimal.ZERO) == 0) {
                return 0;
            }
        }

        ErpOrderInfoStatistics orderInfoStatistics = baseMapper.selectOne(new LambdaQueryWrapper<ErpOrderInfoStatistics>().eq(ErpOrderInfoStatistics::getOrderId, orderId));
        if (orderInfoStatistics == null) {
            String payAmount = sellerOrder.getPayAmount();
            BigDecimal payAmountBig = BigDecimal.ZERO;

            if (StringUtils.isEmpty(payCurrencyCode)) {
                if (childOrderList.size() > 0) {
                    ErpSellerChildOrder childOrder = childOrderList.get(0);
                    payCurrencyCode = childOrder.getProductCurrencyCode();
                }
            }
            if (StringUtils.isNotEmpty(payAmount)) {
                if ("USD".equalsIgnoreCase(payCurrencyCode)) { // 美元
                    payAmountBig = new BigDecimal(payAmount).multiply(exchange);
                } else if ("CUR".equalsIgnoreCase(payCurrencyCode)) { // 欧元
                    payAmountBig = new BigDecimal(payAmount).multiply(exchange);
                } else { // 人民币
                    payAmountBig = new BigDecimal(payAmount);
                }
            }
            // 将基本信息存起来

            if (ObjectUtils.isNotEmpty(childOrderList)) {

                orderInfoStatistics = new ErpOrderInfoStatistics();

                orderInfoStatistics.setOrderId(orderId);
                orderInfoStatistics.setPayPrice(payAmountBig.setScale(2, RoundingMode.HALF_EVEN).toString());
                // 查找店铺
                String sellerLoginId = sellerOrder.getSellerLoginId();
                R<Object> storeEmpowerR = remoteSellerStoreService.getSellerStoreEmpowerByCnCode(sellerLoginId);
                String storeEmpowerString = JSONObject.toJSONString(storeEmpowerR);
                ErpSellerStoreEmpower storeEmpower = JSONObject.parseObject(storeEmpowerString, ErpSellerStoreEmpower.class);
                orderInfoStatistics.setStoreId(storeEmpower.getId().toString());
                Long userId = storeEmpower.getUserId();
                String storeUserName = storeEmpower.getStoreUserName();
                orderInfoStatistics.setStoreUserName(storeUserName);
                // 获取部门
                R<Object> userR = remoteUserService.selectUserById(userId);
                String userString = JSONObject.toJSONString(userR);
                SysUser sysUser = JSONObject.parseObject(userString, SysUser.class);
                orderInfoStatistics.setUserId(userId);
                Long deptId = sysUser.getDeptId();
                orderInfoStatistics.setDeptId(deptId.toString());
                Date gmtCreate = DateUtils.parseDate(sellerOrder.getGmtCreate());
                orderInfoStatistics.setCreateTime(gmtCreate);
                baseMapper.insert(orderInfoStatistics);
                // 子订单信息
                BigDecimal totalInitAmount = BigDecimal.ZERO;
                for (ErpSellerChildOrder childOrder : childOrderList) {
                    String initOrderAmount = childOrder.getInitOrderAmount();
                    totalInitAmount = new BigDecimal(initOrderAmount).add(totalInitAmount);
                }
                for (ErpSellerChildOrder childOrder : childOrderList) {
                    String initOrderAmount = childOrder.getInitOrderAmount();
                    String childOrderId = childOrder.getChildOrderId();
                    String skuCode = childOrder.getSkuCode();
                    Long productCount = childOrder.getProductCount();
                    ErpChildOrderStatistics childOrderStatistics = childOrderStatisticsMapper.selectOne(new LambdaQueryWrapper<ErpChildOrderStatistics>().eq(ErpChildOrderStatistics::getChildOrderId, childOrderId));
                    if (childOrderStatistics == null) {
                        childOrderStatistics = new ErpChildOrderStatistics();
                        childOrderStatistics.setOrderId(orderId);
                        childOrderStatistics.setChildOrderId(childOrderId);
                        childOrderStatistics.setProductCount(productCount.toString());
                        childOrderStatistics.setSkuCode(skuCode);
                        childOrderStatistics.setUserId(userId);
                        childOrderStatistics.setDeptId(deptId);
                        childOrderStatistics.setCreateTime(gmtCreate);
                        childOrderStatistics.setStoreId(storeEmpower.getId());
                        // 获取采集商品id 和 类目id
                        Long productId = childOrder.getProductId();
//                        ErpSellerStoreProduct product = new ErpSellerStoreProduct();
//                        product.setAeProductId(productId);
//                        R<Object> sellerStoreProductR = remoteSellerStoreProductService.getSellerStoreProductInfo(product);
//                        if(sellerStoreProductR.getCode() == 200){
//                            String sellerStoreProductString = JSONObject.toJSONString(sellerStoreProductR.getData());
//                            product = JSONObject.parseObject(sellerStoreProductString, ErpSellerStoreProduct.class);
//                            if (ObjectUtils.isNotNull(product)){
                                //商品不存在
                                ErpCollectProductSku collectProductSku = new ErpCollectProductSku();
                                collectProductSku.setSkuCode(skuCode);
//                                collectProductSku.setCollectProductId(product.getCollectProductId());
                                R<Object> collectProductSkuR = remoteCollectProductService.getCollectProductSkuInfo(collectProductSku);
                                if (collectProductSkuR.getCode() == 200){
                                    String collectProductSkuString = JSONObject.toJSONString(collectProductSkuR.getData());
                                    collectProductSku = JSONObject.parseObject(collectProductSkuString, ErpCollectProductSku.class);
                                    if (collectProductSku != null) {
                                        R<Object> collectProductR = remoteCollectProductService.getCollectProductInfoById(collectProductSku.getCollectProductId());
                                        if(collectProductR.getCode() == 200){
                                            String collectProductString = JSONObject.toJSONString(collectProductR.getData());
                                            ErpCollectProduct collectProduct = JSONObject.parseObject(collectProductString, ErpCollectProduct.class);
                                            if (collectProduct != null) {
                                                Long categoryId = collectProduct.getCategoryId();
                                                childOrderStatistics.setCategoryId(categoryId);
                                            }
                                        }
                                        childOrderStatistics.setCollectProductId(collectProductSku.getCollectProductId());
                                    }
//                                }
//                            }
                        }



                        // 计算子单金额,利润后边算
                        BigDecimal realChildAmount = payAmountBig.multiply(new BigDecimal(initOrderAmount)).divide(totalInitAmount, 2, RoundingMode.HALF_EVEN);
                        childOrderStatistics.setChildAmount(realChildAmount.toString());
                        childOrderStatisticsMapper.insert(childOrderStatistics);
                    }
                }
            }
        }

        // 计算利润,以及预估的成本
        // 先算子单
        if (orderInfoStatistics == null) {
            return 0;
        }
        if (orderInfoStatistics.getProfit() == null) {
            // 订单交易佣金为空,重新算一下
            String escrowFee = orderInfoStatistics.getEscrowFeeRate();
            boolean feeFlag = true; // 是否计算佣金
            if (escrowFee == null || escrowFee.equals("0.00")) {
                String payPrice = orderInfoStatistics.getPayPrice();
                BigDecimal escrow = null;
                BigDecimal afflicate = null;
                ErpSellerChildOrder childOrderOne = childOrderList.get(0);
                String escrowFeeRateStr = childOrderOne.getEscrowFeeRate();
                if (StringUtils.isNotEmpty(escrowFeeRateStr)) {
                    String afflicateFeeRateStr = childOrderOne.getAfflicateFeeRate();
                    R<Object> sellerOrderExtendR = remoteErpOrderService.getByOrderId(orderId.toString());
                    if (sellerOrderExtendR.getCode() == 200){
                        String sellerOrderExtendString = JSONObject.toJSONString(sellerOrderExtendR.getData());
                        ErpSellerOrderExtend orderExtend = JSONObject.parseObject(sellerOrderExtendString, ErpSellerOrderExtend.class);
                        if (orderExtend != null) {
                            String logisticsAmount = orderExtend.getLogisticsAmount();
                            String newOrderAmount = orderExtend.getNewOrderAmount();
                            if (logisticsAmount != null && newOrderAmount != null) {
                                afflicate = new BigDecimal(afflicateFeeRateStr).multiply(new BigDecimal(payPrice));
                                if (!logisticsAmount.equals("0.00")) {
                                    afflicate = (new BigDecimal(newOrderAmount).subtract(new BigDecimal(logisticsAmount)))
                                            .multiply(exchange).multiply(new BigDecimal(afflicateFeeRateStr));
                                }
                                escrow = new BigDecimal(escrowFeeRateStr).multiply(new BigDecimal(payPrice));
                                orderInfoStatistics.setEscrowFeeRate(escrow.setScale(2, RoundingMode.HALF_UP).toString());
                                orderInfoStatistics.setAfflicateFeeRate(afflicate.setScale(2, RoundingMode.HALF_UP).toString());
                                baseMapper.updateById(orderInfoStatistics);
                            } else {
                                feeFlag = false;
                            }
                        } else {
                            feeFlag = false;
                        }
                    }
                }
            }

            // 没有地址,跳过
            AeStoreOrderReceiptAddress address =  remoteAeOrderAddrService.getAddressByOrderId(orderId);
            if (address == null) {
                return 0;
            }
            String country = address.getCountry();
            if (StringUtils.isEmpty(country)) {
                return 0;
            }
            // 如果国家编码是SRB,转为RS
//            String countryCode = dictService.getDictLabel("ae_country_code", "SRB");
            R<String> labelR = remoteDictDataService.getDictLabel("ae_country_code", country, SecurityConstants.INNER);
            if(labelR.getCode() == 200 && labelR.getData() != null){
                country = labelR.getData();
            }
            // sku_price表英国用UK表示
            if (country.equals("GB")) {
                country = "UK";
            }
            orderInfoStatistics.setCountry(country);
            baseMapper.updateById(orderInfoStatistics);

            List<ErpChildOrderStatistics> childOrderStatisticsList = childOrderStatisticsMapper.selectList(new LambdaQueryWrapper<ErpChildOrderStatistics>().eq(ErpChildOrderStatistics::getOrderId, orderId));
            Map<String, Object> map = countChildOrderCost(childOrderStatisticsList, country);
            boolean result = (boolean) map.get("result");
            BigDecimal orderCost =(BigDecimal) map.get("orderCost");
            BigDecimal logisticsCost =(BigDecimal) map.get("logisticsCost");
            if (result) {
                String payPrice = orderInfoStatistics.getPayPrice();
                BigDecimal payPriceBig = new BigDecimal(payPrice);
                if (feeFlag) {
                    BigDecimal es = new BigDecimal(orderInfoStatistics.getEscrowFeeRate());
                    BigDecimal af = new BigDecimal(orderInfoStatistics.getAfflicateFeeRate());
                    BigDecimal orderProfit = payPriceBig.subtract(orderCost).subtract(es).subtract(af).setScale(2, RoundingMode.UP);
                    orderInfoStatistics.setProfit(orderProfit.toString());
                }
                orderInfoStatistics.setPurchaseCost(orderCost.toString());
                orderInfoStatistics.setLogisticsCost(logisticsCost.toString());
                baseMapper.updateById(orderInfoStatistics);
            }
        }
        return 1;
    }


//    @Override
//    public void saveOrderProfitInfo(ErpSellerOrder sellerOrder) {
//        Long orderId = sellerOrder.getOrderId();
//        String payCurrencyCode = sellerOrder.getPayCurrencyCode();
//        List<ErpSellerChildOrder> childOrderList = childOrderService.getChildOrderByOrderId(orderId);
//        if (childOrderList.size() == 0) {
//            return;
//        }
//        // 根据货币获取当时最新汇率
//        if (StringUtils.isEmpty(payCurrencyCode)) {
//            payCurrencyCode = childOrderList.get(0).getProductCurrencyCode();
//        }
//        BigDecimal exchange = usdExchangeService.getExchangeByTime(sellerOrder.getGmtCreate(), payCurrencyCode)
//                .movePointLeft(2);
//        if (exchange.compareTo(BigDecimal.ZERO) == 0) {
//            return;
//        }
//        ErpOrderInfoStatistics orderInfoStatistics = baseMapper.selectOne(new LambdaQueryWrapper<ErpOrderInfoStatistics>().eq(ErpOrderInfoStatistics::getOrderId, orderId));
//        if (orderInfoStatistics == null) {
//            String payAmount = sellerOrder.getPayAmount();
//            BigDecimal payAmountBig = BigDecimal.ZERO;
//
//            if (StringUtils.isEmpty(payCurrencyCode)) {
//                if (childOrderList.size() > 0) {
//                    ErpSellerChildOrder childOrder = childOrderList.get(0);
//                    payCurrencyCode = childOrder.getProductCurrencyCode();
//                }
//            }
//            if (StringUtils.isNotEmpty(payAmount)) {
//                if ("USD".equalsIgnoreCase(payCurrencyCode)) { // 美元
//                    payAmountBig = new BigDecimal(payAmount).multiply(exchange);
//                } else if ("CUR".equalsIgnoreCase(payCurrencyCode)) { // 欧元
//                    payAmountBig = new BigDecimal(payAmount).multiply(exchange);
//                } else { // 人民币
//                    payAmountBig = new BigDecimal(payAmount);
//                }
//            }
//            // 将基本信息存起来
//
//            if (ObjectUtils.isNotEmpty(childOrderList)) {
//
//                orderInfoStatistics = new ErpOrderInfoStatistics();
//
//                orderInfoStatistics.setOrderId(orderId);
//                orderInfoStatistics.setPayPrice(payAmountBig.setScale(2, RoundingMode.HALF_EVEN).toString());
//                // 查找店铺
//                String sellerLoginId = sellerOrder.getSellerLoginId();
//                ErpSellerStoreEmpower storeEmpower = empowerService.selectEmpowerByUserName(sellerLoginId);
//                orderInfoStatistics.setStoreId(storeEmpower.getId().toString());
//                Long userId = storeEmpower.getUserId();
//                String storeUserName = storeEmpower.getStoreUserName();
//                orderInfoStatistics.setStoreUserName(storeUserName);
//                // 获取部门
//                SysUser sysUser = userService.selectUserById(userId);
//                orderInfoStatistics.setUserId(userId);
//                Long deptId = sysUser.getDeptId();
//                orderInfoStatistics.setDeptId(deptId.toString());
//                Date gmtCreate = DateUtils.parseDate(sellerOrder.getGmtCreate());
//                orderInfoStatistics.setCreateTime(gmtCreate);
//                baseMapper.insert(orderInfoStatistics);
//                // 子订单信息
//                BigDecimal totalInitAmount = BigDecimal.ZERO;
//                for (ErpSellerChildOrder childOrder : childOrderList) {
//                    String initOrderAmount = childOrder.getInitOrderAmount();
//                    totalInitAmount = new BigDecimal(initOrderAmount).add(totalInitAmount);
//                }
//                for (ErpSellerChildOrder childOrder : childOrderList) {
//                    String initOrderAmount = childOrder.getInitOrderAmount();
//                    String childOrderId = childOrder.getChildOrderId();
//                    String skuCode = childOrder.getSkuCode();
//                    Long productCount = childOrder.getProductCount();
//                    ErpChildOrderStatistics childOrderStatistics = childOrderStatisticsMapper.selectOne(new LambdaQueryWrapper<ErpChildOrderStatistics>().eq(ErpChildOrderStatistics::getChildOrderId, childOrderId));
//                    if (childOrderStatistics == null) {
//                        childOrderStatistics = new ErpChildOrderStatistics();
//                        childOrderStatistics.setOrderId(orderId);
//                        childOrderStatistics.setChildOrderId(childOrderId);
//                        childOrderStatistics.setProductCount(productCount.toString());
//                        childOrderStatistics.setSkuCode(skuCode);
//                        childOrderStatistics.setUserId(userId);
//                        childOrderStatistics.setDeptId(deptId);
//                        childOrderStatistics.setCreateTime(gmtCreate);
//                        childOrderStatistics.setStoreId(storeEmpower.getId());
//                        // 获取采集商品id 和 类目id
//                        Long productId = childOrder.getProductId();
//                        ErpSellerStoreProduct product = erpSellerStoreProductMapper.selectOne(
//                                new LambdaQueryWrapper<ErpSellerStoreProduct>().eq(ErpSellerStoreProduct::getAeProductId,productId)
//                        );
//                        if (ObjectUtils.isNotNull(product)){
//                         //商品不存在
//                            ErpCollectProductSku collectProductSku = collectProductSkuMapper.selectOne(
//                                    new LambdaQueryWrapper<ErpCollectProductSku>()
//                                            .eq(ErpCollectProductSku::getSkuCode, skuCode)
//                                            .eq(ErpCollectProductSku::getCollectProductId, product.getCollectProductId())
//                            );
//
//                            if (collectProductSku != null) {
//                                Long collectProductId = collectProductSku.getCollectProductId();
//                                ErpCollectProduct collectProduct = collectProductMapper.selectById(collectProductId);
//                                if (collectProduct != null) {
//                                    Long categoryId = collectProduct.getCategoryId();
//                                    childOrderStatistics.setCategoryId(categoryId);
//                                }
//                                childOrderStatistics.setCollectProductId(collectProductId);
//                            }
//                        }
//
//
//                        // 计算子单金额,利润后边算
//                        BigDecimal realChildAmount = payAmountBig.multiply(new BigDecimal(initOrderAmount)).divide(totalInitAmount, 2, RoundingMode.HALF_EVEN);
//                        childOrderStatistics.setChildAmount(realChildAmount.toString());
//                        childOrderStatisticsMapper.insert(childOrderStatistics);
//                    }
//                }
//            }
//        }
//
//        // 计算利润,以及预估的成本
//        // 先算子单
//        if (orderInfoStatistics == null) {
//            return;
//        }
//        if (orderInfoStatistics.getProfit() == null) {
//            // 订单交易佣金为空,重新算一下
//            String escrowFee = orderInfoStatistics.getEscrowFeeRate();
//            boolean feeFlag = true; // 是否计算佣金
//            if (escrowFee == null || escrowFee.equals("0.00")) {
//                String payPrice = orderInfoStatistics.getPayPrice();
//                BigDecimal escrow = null;
//                BigDecimal afflicate = null;
//                ErpSellerChildOrder childOrderOne = childOrderList.get(0);
//                String escrowFeeRateStr = childOrderOne.getEscrowFeeRate();
//                if (StringUtils.isNotEmpty(escrowFeeRateStr)) {
//                    String afflicateFeeRateStr = childOrderOne.getAfflicateFeeRate();
//                    ErpSellerOrderExtend orderExtend = orderExtendMapper.selectOne(new LambdaQueryWrapper<ErpSellerOrderExtend>().eq(ErpSellerOrderExtend::getOrderId, orderId));
//                    if (orderExtend != null) {
//                        String logisticsAmount = orderExtend.getLogisticsAmount();
//                        String newOrderAmount = orderExtend.getNewOrderAmount();
//                        if (logisticsAmount != null && newOrderAmount != null) {
//                            afflicate = new BigDecimal(afflicateFeeRateStr).multiply(new BigDecimal(payPrice));
//                            if (!logisticsAmount.equals("0.00")) {
//                                afflicate = (new BigDecimal(newOrderAmount).subtract(new BigDecimal(logisticsAmount)))
//                                        .multiply(exchange).multiply(new BigDecimal(afflicateFeeRateStr));
//                            }
//                            escrow = new BigDecimal(escrowFeeRateStr).multiply(new BigDecimal(payPrice));
//                            orderInfoStatistics.setEscrowFeeRate(escrow.setScale(2, RoundingMode.HALF_UP).toString());
//                            orderInfoStatistics.setAfflicateFeeRate(afflicate.setScale(2, RoundingMode.HALF_UP).toString());
//                            baseMapper.updateById(orderInfoStatistics);
//                        } else {
//                            feeFlag = false;
//                        }
//                    } else {
//                        feeFlag = false;
//                    }
//                }
//            }
//
//            // 没有地址,跳过
//            AeStoreOrderReceiptAddress address = addressMapper.selectOne(new LambdaQueryWrapper<AeStoreOrderReceiptAddress>().eq(AeStoreOrderReceiptAddress::getOrderId, orderId));
//            if (address == null) {
//                return;
//            }
//            String country = address.getCountry();
//            if (StringUtils.isEmpty(country)) {
//                return;
//            }
//            // 如果国家编码是SRB,转为RS
////            String countryCode = dictService.getDictLabel("ae_country_code", "SRB");
//            SysDictData dictData = dictDataMapper.selectLabelByValue("ae_country_code", country);
//            if (dictData != null) {
//                country = dictData.getDictLabel();
//            }
//            // sku_price表英国用UK表示
//            if (country.equals("GB")) {
//                country = "UK";
//            }
//            orderInfoStatistics.setCountry(country);
//            baseMapper.updateById(orderInfoStatistics);
//
//            List<ErpChildOrderStatistics> childOrderStatisticsList = childOrderStatisticsMapper.selectList(new LambdaQueryWrapper<ErpChildOrderStatistics>().eq(ErpChildOrderStatistics::getOrderId, orderId));
//            Map<String, Object> map = countChildOrderCost(childOrderStatisticsList, country);
//            boolean result = (boolean) map.get("result");
//            BigDecimal orderCost =(BigDecimal) map.get("orderCost");
//            BigDecimal logisticsCost =(BigDecimal) map.get("logisticsCost");
//            if (result) {
//                String payPrice = orderInfoStatistics.getPayPrice();
//                BigDecimal payPriceBig = new BigDecimal(payPrice);
//                if (feeFlag) {
//                    BigDecimal es = new BigDecimal(orderInfoStatistics.getEscrowFeeRate());
//                    BigDecimal af = new BigDecimal(orderInfoStatistics.getAfflicateFeeRate());
//                    BigDecimal orderProfit = payPriceBig.subtract(orderCost).subtract(es).subtract(af).setScale(2, RoundingMode.UP);
//                    orderInfoStatistics.setProfit(orderProfit.toString());
//                }
//                orderInfoStatistics.setPurchaseCost(orderCost.toString());
//                orderInfoStatistics.setLogisticsCost(logisticsCost.toString());
//                baseMapper.updateById(orderInfoStatistics);
//            }
//        }
//    }
//
    public Map<String,Object> countChildOrderCost(List<ErpChildOrderStatistics> childOrderStatisticsList, String country) {

        boolean whetherProfit = true;
        HashMap<String, Object> map = new HashMap<>();
        BigDecimal orderCost = BigDecimal.ZERO; // 订单
        BigDecimal logisticsCost = BigDecimal.ZERO;
        for (ErpChildOrderStatistics childOrderStatistics : childOrderStatisticsList) {
            String skuCode = childOrderStatistics.getSkuCode();
            String productCount = childOrderStatistics.getProductCount();
            String childOrderId = childOrderStatistics.getChildOrderId();

            ErpSellerChildOrder childOrder = remoteErpChildOrderService.getChildByChildId(childOrderId);
            if (childOrder == null) {
                map.put("result",false);
                return map;
            }
            String logisticsType = childOrder.getLogisticsType();
            Long collectProductId = childOrderStatistics.getCollectProductId();
            Integer templateId = null;
            // 获取商品的属性
            
            ErpCollectProductExpand collectProductExpand = new ErpCollectProductExpand();
            collectProductExpand.setCollectProductId(childOrderStatistics.getCollectProductId());
            R<Object> collectProductExpandR = remoteCollectProductService.getCollectProductExpandInfo(collectProductExpand);

            if(collectProductExpandR.getCode() == 200){
                String collectProductExpandStr = JSONObject.toJSONString(collectProductExpandR.getData());
                collectProductExpand = JSONObject.parseObject(collectProductExpandStr, ErpCollectProductExpand.class);
                templateId = collectProductExpand.getTemplateId();
            }else {
                whetherProfit = false;
                continue;
            }
            if (ObjectUtils.isNull(collectProductExpand)) {
                templateId = 0;
            } else if (ObjectUtils.isNotNull(collectProductExpand.getTemplateId()) && collectProductExpand.getTemplateId() != 7) {
                templateId = judgeBuyerLogistics(logisticsType, collectProductId);
            }
            R<Object> skuPriceR = remoteCollectProductSkuPriceService.getBySkuCode(skuCode);
            if(skuPriceR.getCode() != 200){
                map.put("result",false);
                return map;
            }
            String skuPriceStr = JSONObject.toJSONString(skuPriceR.getData());
            ErpCollectProductSkuPrice bySkuCode = JSONObject.parseObject(skuPriceStr, ErpCollectProductSkuPrice.class);
            if (bySkuCode != null) {
                String globalQuoteMap = bySkuCode.getGlobalQuoteMap();
                String costUnitPrice = null; // 单个商品采购成本
                if (StringUtils.isEmpty(globalQuoteMap)) {
                    whetherProfit = false;
                    continue;
                } else {
                    Map<String, Object> globalMap = JSON.parseObject(globalQuoteMap);
                    costUnitPrice = (String) globalMap.get(country);
                    if (costUnitPrice == null) {
                        // 判断是否全球包邮
                        if (collectProductExpand.getTemplateId() == 7) {
                            costUnitPrice = (String) globalMap.get("US");
                            if (costUnitPrice == null) {
                                whetherProfit = false;
                                continue;
                            }
                        }else {
                            whetherProfit = false;
                            continue;
                        }
                    }
                }

                String productUnitPrice = bySkuCode.getOriginalSkuPrice(); // 原始sku单价
                if (productUnitPrice.equals("0")) {
                    productUnitPrice = bySkuCode.getSkuPrice();
                }
                String productTotalPrice = productUnitPrice; // 原始sku总价

                String freightMap = bySkuCode.getFreightMap();
                Map<String, Object> freMap = JSON.parseObject(freightMap);
                BigDecimal logisticsUnitPrice = BigDecimal.ZERO; // 物流单价
                BigDecimal logisticsTotalPrice = BigDecimal.ZERO; // 物流总价
                BigDecimal costTotalPrice = BigDecimal.ZERO; // 总成本
                if (ObjectUtils.isNotEmpty(freMap)) {
                    Object fre = freMap.get(country);// 单个商品的物流价格
                    if (ObjectUtils.isNotEmpty(fre)) {
                        logisticsUnitPrice = new BigDecimal(fre.toString());
                    }
                }
                if (Integer.parseInt(productCount) == 1) {
                    logisticsTotalPrice = logisticsUnitPrice;
                    costTotalPrice = new BigDecimal(costUnitPrice);
                }
                if (Integer.parseInt(productCount) != 1 || templateId != null){
                    // 获取到sku信息进行运费试算
                    ErpCollectProductSku collectProductSku = new ErpCollectProductSku();
                    collectProductSku.setSkuCode(skuCode);
                    collectProductSku.setDelFlag("0");
                    List<ErpCollectProductSku> collectProductSkuList = remoteCollectProductSkuService.getCollectProductSkuList(collectProductSku);

                    if (!collectProductSkuList.isEmpty()) {
                        collectProductSku = collectProductSkuList.get(0);
                        if (collectProductSku == null) {
                            whetherProfit = false;
                            continue;
                        }
                        BigDecimal skuWidth = collectProductSku.getSkuWidth();
                        Long skuWeight = collectProductSku.getSkuWeight() * Long.parseLong(productCount);
                        BigDecimal skuHeight = collectProductSku.getSkuHeight();
                        BigDecimal skuLength = collectProductSku.getSkuLength();
                        
//                    if (!productAttribute.equals("0")) {
//                        productAttribute = "1";
//                    }
//                    logisticsTotalPrice = productFreightService.calculateFreightByCaiNiao(country, Long.toString(skuWeight), skuWidth.toString(), skuHeight.toString(), skuLength.toString(), productAttribute);
                        ErpProductExistingFreightRecord productFreight = new ErpProductExistingFreightRecord();
                        if (country.equals("UK"))
                            country = "GB";
                        productFreight.setCountry(country);
                        productFreight.setWidth(skuWidth.toString());
                        productFreight.setWeight(skuWeight.toString());
                        productFreight.setHeight(skuHeight.toString());
                        productFreight.setLength(skuLength.toString());
                        productFreight.setType(templateId);
                        R<String> freightR = remoteFreightService.calculateFreight(productFreight);
                        logisticsTotalPrice = new BigDecimal(freightR.getData());
                        if (templateId == 7) {
                            // 全球包邮2.0，运费试算 0
                            logisticsTotalPrice = BigDecimal.ZERO;
                        }
                        R<Object> configKey = configService.getConfigKey("logistics_ratio");
                        String logisticsRatio = configKey.getMsg();; // 百分比 110%
                        logisticsTotalPrice = logisticsTotalPrice.multiply(new BigDecimal(logisticsRatio).movePointLeft(2)).setScale(2, RoundingMode.HALF_UP); // 最终物流价格
                        // 子订单的最终成本 = 商品原始价格 * 数量 + 最终的运费价格 (保留两位小数)
                        productTotalPrice = new BigDecimal(productUnitPrice).multiply(new BigDecimal(productCount)).toString();
                        costTotalPrice = (new BigDecimal(productTotalPrice).add(logisticsTotalPrice));
                    }
                }
                // 计算子单利润 (金额 - 佣金 - 成本)
                String childAmount = childOrderStatistics.getChildAmount();
                String escrowFeeRate = childOrder.getEscrowFeeRate();
                String afflicateFeeRate = childOrder.getAfflicateFeeRate();
                if (escrowFeeRate != null && afflicateFeeRate != null) {
                    BigDecimal childAmountBig = new BigDecimal(childAmount);
                    BigDecimal escrow = new BigDecimal(escrowFeeRate).multiply(childAmountBig).setScale(2, RoundingMode.UP);
                    BigDecimal afflicate = new BigDecimal(afflicateFeeRate).multiply(childAmountBig).setScale(2, RoundingMode.UP);
                    BigDecimal childProfit = childAmountBig.subtract(escrow).subtract(afflicate).subtract(costTotalPrice);
                    childOrderStatistics.setProductProfit(childProfit.setScale(2, RoundingMode.UP).toString());
                }else {
                    whetherProfit = false;
                }
                childOrderStatistics.setCostUnitPrice(costUnitPrice);
                childOrderStatistics.setCostTotalPrice(costTotalPrice.setScale(2, RoundingMode.HALF_UP).toString());
                childOrderStatistics.setLogisticsUnitPrice(logisticsUnitPrice.toString());
                childOrderStatistics.setLogisticsTotalPrice(logisticsTotalPrice.setScale(2, RoundingMode.HALF_UP).toString());
                childOrderStatistics.setProductUnitPrice(productUnitPrice);
                childOrderStatistics.setProductTotalPrice(productTotalPrice);
                childOrderStatisticsMapper.updateById(childOrderStatistics);
                orderCost = costTotalPrice.add(orderCost);
                logisticsCost = logisticsTotalPrice.add(logisticsCost);
            } else {
                whetherProfit = false;
            }
        }
//        HashMap<String, Object> map = new HashMap<>();
        map.put("result",whetherProfit);
        map.put("orderCost",orderCost);
        map.put("logisticsCost",logisticsCost);
        return map;
    }
//
    /**
     * 判断买家选择物流
     */
    private Integer judgeBuyerLogistics(String logisticsType, Long collectProductId) {
        if (collectProductId == null) {
            return null;
        }
        ErpCollectProductExpand collectProductExpand = new ErpCollectProductExpand();
        collectProductExpand.setCollectProductId(collectProductId);
        R<Object> collectProductExpandR = remoteCollectProductService.getCollectProductExpandInfo(collectProductExpand);
        if(collectProductExpandR.getCode() != 200){
            return null;
        }
        String collectProductExpandStr = JSONObject.toJSONString(collectProductExpandR.getData());
        collectProductExpand = JSONObject.parseObject(collectProductExpandStr, ErpCollectProductExpand.class);
        if (collectProductExpand == null) {
            return null;
        }
        Integer templateId = collectProductExpand.getTemplateId();
        if (templateId == null) {
            return null;
        }
        switch (logisticsType) {
            case "CAINIAO_STANDARD":
            case "CAINIAO_STANDARD_SG":
            case "CAINIAO_CONSOLIDATION_SA":

                return templateId == 0 ? null : 0;
            case "CAINIAO_STANDARD_HEAVY":
                return templateId == 3 ? null : 3;
            case "AE_CN_SUPER_ECONOMY_G":
                return templateId == 4 ? null : 4;
        }
        return null;
    }
//
//    @Override
//    public void deleteStaticInfo(Long orderId) {
//        childOrderStatisticsMapper.delete(new LambdaQueryWrapper<ErpChildOrderStatistics>().eq(ErpChildOrderStatistics::getOrderId, orderId));
//        baseMapper.deleteById(orderId);
//    }
//

}
